package nl.windgazer.arachne.util;

import org.apache.tapestry5.dom.Document;
import org.apache.tapestry5.dom.Element;

/**
 * A convenience class to easily add elements to the HEAD of a page. Two defaults are added as
 * script and style are, to me, quite common additions to a page. Since in this method the script
 * is always added to the head it may be used for adding initialization scripts that need to run
 * before the page starts rendering (useful when your scripts only enrich the page but the page
 * needs to look slightly different if JS is disabled)
 * @author mreuring
 *
 */
public class HtmlHeadBlocks {

	/**
	 * Write a style element to the head of the page. Especially useful for adding external
	 * content with its' own custom CSS-rules.
	 * @param style
	 * @param doc
	 */
	public static Element writeStyleBlock(String style, Document doc) {
		return writeBlock(style, "style", "text/css", doc);
	}

	/**
	 * Write a script element to the head of the page. Useful for adding js to the page that
	 * notifies the html by use of classNames on the body, or similar construct that have to
	 * run before the page starts rendering. Even though this is possible using T5, in T5 the
	 * result is that _all_ scripts will be loading from the head, while the default setting
	 * of loading scripts last has good reasoning behind it.
	 * @param script
	 * @param doc
	 */
	public static Element writeScriptBlock(String script, Document doc) {
		return writeBlock(script, "script", "text/javascript", doc);
 	}

	/**
	 * Since essentially a script or style element only differs in the name, this method contains
	 * the generic code for writing any element into the head of the page.
	 * 
	 * @param content
	 * @param element
	 * @param type
	 * @param doc
	 */
	public static Element writeBlock(String content, String element, String type, Document doc) {
        final Element head = getHead(doc);
        if (head != null) {
        	final Element block = head.element(element, "type", type);
	        block.cdata(content);
	        return block;
        }
        return null;
	}
	
	public static Element getHead(Document doc) {
		final Element head = doc.find("html/head");
        return head;
	}

}
